<!-- 运维费用 改名 运维对账 -->
<template>
  <div class="page-container">
    <div class="quick-search">
      <div
        v-for="item in quickSearchData"
        :key="item.key"
        class="quick-search-item"
        :class="[item.checked ? 'quick-search-item-checked' : '']"
        @click="quickSearchClick(item)"
      >
        <div class="quick-search-item-label">{{ item.label }}</div>
        <div class="quick-search-item-value" :class="[item.checked ? 'quick-search-item-value-checked' : '']">{{ item.value + '元' }}</div>
      </div>
    </div>
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" @reset="searcherChange" />

    <table-index
      :table="tableCompulsory"
      :selectedKeys="selectedRowKeys"
      @loadData="loadData"
      @selection-change="selectionChange"
      @pagenationChange="pagenationChange"
      :row-class="getRowClassName"
    >
      <template #expand-icon="{ expanded }">
        <icon-plus-circle style="font-size: 20px; color: #0256ff" v-if="!expanded" />
        <icon-minus-circle style="font-size: 20px; color: #0256ff" v-else />
      </template>
      <template #carInfo="{ record }">
        <div>
          <!-- 历史车牌号 -->
          <span :style="{ marginRight: record.licenseNo !== record.carLicenseNo ? '6px' : 0 }">{{ record.licenseNo }}</span>
          <!-- 现车牌号：如果历史车牌号与现车牌号不一致，则显示 -->
          <tag v-if="record.licenseNo !== record.carLicenseNo" type="primary">现：{{ record.carLicenseNo }}</tag>
        </div>
        <div>{{ record.carModelName }}</div>
      </template>
      <template #bindOrder="{ record }">
        <div
          ><span @click="() => onLink(record)" v-if="record.orderCode" class="order-line">{{ record.orderCode }}</span>
          <span v-else>-</span>
        </div>
        <div>交车人：{{ record.staffName || '-' }}</div>
      </template>
      <template #undermsg="{ record }">
        <div>{{ record.undertaker }}</div>
        <div>{{ record.undertakerTel }}</div>
      </template>
    </table-index>
  </div>
  <fee ref="feepage" @ok="feepageConfirm" />
  <!-- 维修 编辑费用 -->
  <mainEditFeeModal ref="maineditfee" @feepageConfirm="feepageConfirm" />
  <!-- 年检/保养 编辑费用 -->
  <editFee ref="editFeeRef" @ok="feepageConfirm" />
</template>

<script setup lang="tsx" name="MaintenanceReconciliationList">
  import mainEditFeeModal from '@/views/editFee/mainFee/index.vue'
  import editFee from '@/views/assets/compnoents/editFee.vue'
  import { reactive, onMounted, computed, ref } from 'vue'
  import { useTable } from '@/hooks/table'
  import { useExport } from '@/hooks/list'
  import { evalQueryParam } from '@/utils'
  import {
    getOperationsCostPageList,
    exportOperationsCostExcel,
    getOperationsCostStatistics,
    checkManyToConfirm,
  } from '@/api/finance/costConfirm.js'
  import useNavigate from '@/hooks/useNavigate'
  import { usePageDict } from '@/hooks/useDict'
  import dayjs from 'dayjs'
  import { useRoute } from 'vue-router'
  import fee from '@/views/confirmFee/maintenance/index.vue'
  import { Message } from '@arco-design/web-vue'
  const route = useRoute()
  const routeQuery = route.query
  console.log('routeQuery', routeQuery)
  const dict = usePageDict('carAssetFeeDict')
  const { navigateTo } = useNavigate()
  const feepage = ref(null)
  const maineditfee = ref()
  const editFeeRef = ref()
  const quickSearchData = ref([
    {
      key: 1,
      label: '本月付款总额',
      value: 0,
      checked: false,
    },
    {
      key: 2,
      label: '待付款费用',
      value: 0,
      checked: false,
    },
  ])
  const oldIdList = ref(null)
  const searchList = computed(() => {
    return [
      {
        label: '车牌号',
        prop: 'licenseNoLike',
        type: 'a-input',
      },
      {
        label: '费用名称',
        prop: 'feeNameIdList',
        type: 'a-select',
        options: dict.operationsCostFeeNameId,
        multiple: true,
      },
      {
        label: '运维单关联门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'multiple_site_listBystaff',
          params: {
            idList: oldIdList.value,
          },
        },
      },
      {
        label: '费用状态',
        prop: 'feeStatuses',
        type: 'a-select',
        options: dict.operationsCostFeeStatus,
        attrs: {
          multiple: true,
        },
      },

      { label: '业务单信息', prop: 'businesCode', type: 'a-input' },
      {
        label: '负责人',
        prop: 'undertakerIdsList',
        type: 'remote-select',
        attrs: {
          mode: 'multiple',
          type: 'store_staff_list_multiple',
        },
      },
      {
        label: '供应商',
        prop: 'supplierIdList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'supplier_list_multiple',
        },
      },
      {
        label: '应结时间',
        prop: 'createTimeRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:23:59'],
          },
        },
        change: (value = []) => {
          queryParam.dueStartDate = value[0]
          queryParam.dueEndDate = value[1]
        },
      },
      {
        label: '运维周期',
        prop: 'dateRange',
        type: 'i-range-picker',
        timePickerProps: {
          showTime: true,
          defaultValue: ['00:00:00', '23:59:59'],
        },
        change: (value = []) => {
          queryParam.startTime = value[0]
          queryParam.endTime = value[1]
        },
      },
    ]
  })
  // 筛选发生变化时，清除统计样式
  const searcherChange = () => {
    selectedRowKeys.value = []
    quickSearchData.value.forEach((i) => {
      i.checked = false
    })
  }
  //快捷查询
  const quickSearchClick = (item) => {
    queryParam.createTimeRange = []
    queryParam.dueStartDate = undefined
    queryParam.dueEndDate = undefined
    queryParam.feeStatuses = []
    quickSearchData.value.forEach((ele) => {
      if (ele.key == item.key) {
        ele.checked = true
      } else {
        ele.checked = false
      }
    })
    if (item.key == 1) {
      let dueStartDate = dayjs().startOf('month').format('YYYY-MM-DD 00:00:00')
      let dueEndDate = dayjs().format('YYYY-MM-DD 23:59:59')
      queryParam.createTimeRange[0] = dueStartDate
      queryParam.createTimeRange[1] = dueEndDate
      queryParam.dueStartDate = dueStartDate
      queryParam.dueEndDate = dueEndDate
      queryParam.feeStatuses = [0, 1, 5]
    }
    if (item.key == 2) {
      queryParam.feeStatuses = [0, 5]
    }
    loadData()
  }
  const tableCompulsory = useTable({
    pagination: {
      page: 1,
      pageSize: 10,
      showSizePicker: true,
      pageCount: 1,
      pageSizes: [10, 20, 50],
    },
    columns: [
      {
        title: '费用应结日期',
        dataIndex: 'dueDate',
        fixed: 'left',
        width: 140,
        render: (record: any) => {
          if (record.dueDate) return dayjs(record.dueDate).format('YYYY-MM-DD')
          // 优化不显示横线
          return <span></span>
        },
      },
      { title: '车辆信息', dataIndex: 'carInfo', slotName: 'carInfo', width: 240, fixed: 'left' },
      { title: '费用名称', dataIndex: 'feeName', width: 100 },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 100 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 90 },
      { title: '费用金额', dataIndex: 'totalAmount', unit: '元', width: 110 },
      { title: '待结金额', dataIndex: 'outstandingAmount', unit: '元', width: 110 },
      { title: '生成节点', dataIndex: 'createNodeName', width: 100 },
      { title: '生成时间', dataIndex: 'createTime', width: 170 },
      { title: '收支方式', dataIndex: 'payTypeName', width: 100 },
      { title: '费用状态', dataIndex: 'feeStatusName', width: 100 },
      { title: '结算时间', dataIndex: 'confirmTime', width: 170 },
      { title: '结算人', dataIndex: 'confirmUserName', width: 80 },
      // { title: '备注', dataIndex: 'remark' },
      { title: '关联单号', dataIndex: 'order', slotName: 'bindOrder', width: 170 },
      { title: '业务单信息', dataIndex: 'businesCode', width: 150 },
      { title: '负责人', dataIndex: 'sit', slotName: 'undermsg', width: 130 },
      { title: '供应商', dataIndex: 'supplierName', width: 190 },
      { title: '运维单关联门店', dataIndex: 'siteName', width: 150 },
      {
        title: '运维时间',
        dataIndex: 'time',
        width: 180,
        render: (record) => {
          // feeCategory: 1 保养费 2 维修费 3 年检费
          if (record.feeCategory == 2) {
            return (
              <div>
                <div>{record.startTime}-</div>
                <div>{record.endTime}</div>
              </div>
            )
          } else {
            return record.startTime ? dayjs(record.startTime).format('YYYY-MM-DD') : '-'
          }
        },
      },
    ],
    operates: [
      {
        label: '结算',
        permission: 'svms:finance:reconciliation:maintenancefee.confirm',
        show: (record) => record.level == 1 && (record.feeStatus == 0 || record.feeStatus == 5),
        method: (record) => {
          feepage.value.show([record.id])
        },
      },
      {
        label: '修改费用',
        permission: 'svms:finance:reconciliation:maintenancefee.edit',
        show: (record) => record.level == 1 && (record.feeStatus == 0 || record.feeStatus == 5),
        method: (record) => {
          if (record.feeCategory == 2) {
            maineditfee.value.show(record.id, record.feeCategory)
          } else {
            editFeeRef.value.show(record.id, record.feeCategory)
          }
        },
      },
    ],
    buttons: [
      {
        mode: 'export',
        permission: 'svms:finance:reconciliation:maintenancefee.export',
        label: '导出',
        method: () => handleExport(),
      },
      {
        type: 'primary',
        label: '批量结算',
        permission: 'svms:finance:reconciliation:maintenancefee.barchConfirm',
        method: () => handleBatchConfirm(),
      },
    ],
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
  })
  const onLink = (record) => {
    if (record.orderType == 2) {
      navigateTo(`/short-order/detail/${record.orderId}`, `${record.orderCode}-短租详情`)
    } else if (record.orderType == 3) {
      navigateTo(`/long-order/detail/${record.orderId}`, `${record.orderCode}-长租详情`)
    }
  }
  // 导出事件
  const handleExport = () => {
    useExport(exportOperationsCostExcel, queryParam)
  }

  // 选择 keys
  const selectedRowKeys = ref([])
  const checkboxChange = (e, id) => {
    const index = selectedRowKeys.value.indexOf(id)
    if (index > -1) {
      selectedRowKeys.value.splice(index, 1)
    } else {
      selectedRowKeys.value.push(id)
    }
  }
  const setValue = computed(() => {
    let obj = {}
    selectedRowKeys.value.forEach((it) => {
      obj[it] = true
    })
    return obj
  })
  // 页数选择后清空 复选框
  const pagenationChange = () => {
    selectedRowKeys.value = []
  }
  const selectionChange = (e) => {
    selectedRowKeys.value = e
  }
  const handleBatchConfirm = () => {
    if (selectedRowKeys.value.length) {
      console.log(selectedRowKeys.value)
      checkManyToConfirm({ idList: selectedRowKeys.value }).then((res: any) => {
        if (res.code == 200) {
          feepage.value.show(selectedRowKeys.value)
        } else {
          Message.error(res.message)
        }
      })
    } else {
      Message.warning('请先勾选需要确认的数据！')
    }
  }
  const queryParam = reactive({
    feeStatuses: [0, 5],
    siteIdList: [],
  })
  const loadData = () => {
    queryParam.pageNumber = tableCompulsory.pagination.page || 1
    queryParam.pageSize = tableCompulsory.pagination.pageSize
    tableCompulsory.tableLoading = true
    selectedRowKeys.value = []
    getOperationsCostPageList(queryParam)
      .then((res) => {
        const result = res.result.data
        const data = tabletolist(result) //表
        data.map((it) => (it.disabled = ![0, 5].includes(it.feeStatus)))
        tableCompulsory.dataList = data
        tableCompulsory.pagination.pageCount = res.result.total
      })
      .finally(() => {
        tableCompulsory.tableLoading = false
      })
  }
  const getStatic = async () => {
    const { result } = await getOperationsCostStatistics()
    quickSearchData.value[0].value = result.totalPayment
    quickSearchData.value[1].value = result.paymentExpenses
  }
  // 字段处理
  const tabletolist = (list) => {
    list.forEach((el) => {
      el.mtype = 'MENU'
      el.level = 1
      // feeCategory: 1 保养费 2 维修费 3 年检费
      // 维修展示展开收起，保养、年检不展示
      const feeCategory = el.feeCategory
      if (feeCategory == 2 && el.feeDetailList && el.feeDetailList.length) {
        el.children = el.feeDetailList
        el.children.forEach((pl) => {
          pl.id = pl.id + 10000 //因折叠根据id问题(父子级id相同)，数据只做展示，故自定义
          pl.mtype = 'TERM1'
          pl.expand = null
          pl.feeName = pl.itemName
          pl.totalAmount = pl.amount
          pl.disabled = true
          pl.isClass = true
        })
      } else {
        return false
      }
    })
    return list
  }
  // 确认成功
  const feepageConfirm = () => {
    console.log('确认成功')
    loadData()
    getStatic()
  }

  const getRowClassName = (record: any) => {
    return record.isClass ? 'arco-table-tr-expand' : ''
  }

  onMounted(() => {
    if (routeQuery.refCode) {
      queryParam.businesCode = routeQuery.refCode
      queryParam.feeStatuses = []
    }
    // 付款状态
    if (route.query.feeStatuses) {
      let feeStatuses = evalQueryParam(route.query.feeStatuses)
      queryParam.feeStatuses = feeStatuses
    }
    // 运维单关联门店
    if (route.query.siteIdList) {
      let siteIdList = evalQueryParam(route.query.siteIdList)
      siteIdList = siteIdList.map((item) => String(item))
      queryParam.siteIdList = siteIdList
      oldIdList.value = siteIdList
    }
    // 应结时间
    if (route.query.startTime) {
      let startTime = route.query.startTime
      let endTime = route.query.endTime
      startTime = dayjs(startTime).format('YYYY-MM-DD 00:00:00')
      endTime = dayjs(endTime).format('YYYY-MM-DD 23:59:59')
      queryParam.dueStartDate = startTime
      queryParam.dueEndDate = endTime
      queryParam.createTimeRange = [startTime, endTime]
    }
    // 费用名称
    if (route.query.feeNameIdList) {
      let feeNameIdList = evalQueryParam(route.query.feeNameIdList)
      queryParam.feeNameIdList = feeNameIdList
    }

    loadData()
    getStatic()
  })
</script>

<style lang="less" scoped>
  .check-box {
    margin-top: 4px;
  }
  .content-item {
    .content-item-name {
      margin-bottom: 4px;
      .staff-can-click {
        color: rgb(var(--primary-6));
        cursor: pointer;
      }
      .tag-pickup {
        padding: 0 3px;
        line-height: 18px;
      }
      :deep(.custom-tag) {
        margin-right: 6px;
        position: relative;
        top: 1px;
      }
    }
    .content-item-tag :deep(.custom-tag.default) {
      line-height: 20px;
      padding: 4px 8px;
    }
  }
  .content-item + .content-item {
    margin-top: 10px;
  }
  .quick-search {
    display: flex;
    margin-bottom: 20px;
  }
  .quick-search-item {
    width: 16%;
    height: 62px;
    padding: 9px 0 9px 16px;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #e5e8ef;
    cursor: pointer;
  }
  .quick-search-item:hover {
    transform: scale(1.1);
    transition: transform 0.3s;
    position: relative;
    z-index: 999;
  }
  .quick-search-item-checked {
    background: #e8f3ff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #1890ff;
  }
  .quick-search-item:nth-of-type(n + 2) {
    margin-left: 20px;
  }
  .quick-search-item-label {
    font-size: 12px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #4e5969;
  }
  .quick-search-item-value {
    font-size: 20px;
    font-family: PingFang SC-Semibold, PingFang SC;
    font-weight: 600;
    color: #1d2129;
  }
  .quick-search-item-value-checked {
    color: #1890ff;
  }
  :deep(.arco-table-expand-btn) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  :deep(.arco-table-expand-btn:hover) {
    width: 20px;
    height: 20px;
    background-color: inherit;
  }
  .order-line {
    color: #165dff;
    font-size: 12px;
    text-decoration: underline;
    cursor: pointer;
  }
</style>
